package com.gome.ocean.service.yugong.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import com.gome.ocean.dao.model.yugong.YgManagerBO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gome.ocean.common.constants.YugongContants;
import com.gome.ocean.common.enums.DisabledStatus;
import com.gome.ocean.common.enums.OccupyStatus;
import com.gome.ocean.common.exception.YugongUploadException;
import com.gome.ocean.common.utils.IOUtils;
import com.gome.ocean.dao.model.yugong.YgTaskBO;
import com.gome.ocean.service.yugong.YgManagerService;
import com.gome.ocean.service.yugong.YugongService;

@Service
public class YugongServiceImpl implements YugongService {

    private static final Logger LOG = LoggerFactory.getLogger(YugongServiceImpl.class);

    private static final String DEFAULT_YUGONG = "yugong.properties";

    @Autowired
    private YgManagerService ygManagerService;

    @Override
    public boolean uploadYugongConfig(YgTaskBO taskBO) throws YugongUploadException {
        if (taskBO == null || taskBO.getManagerId() == null) return false;

        YgManagerBO ygManager = ygManagerService.findYgManagerBOById(taskBO.getManagerId());
        if (OccupyStatus.OCCUPY == OccupyStatus.getOccupyStatus(ygManager.getIsOccupy())) {
            LOG.debug("yugong manager is occupy!ygManagerBO:" + ygManager);
            return false;
        }

        if (DisabledStatus.DISABLED == DisabledStatus.getDisabledStatus(ygManager.getIsDisabled())) {
            LOG.debug("yugong manager is disabled!ygManagerBO:" + ygManager);
            return false;
        }
        try {
            String yugongConfig = taskBO.getContext();
            OutputStream outputStream = new FileOutputStream(
                new File(YugongContants.getYugongConfPath(ygManager.getYgLocation()).concat(DEFAULT_YUGONG)));
            IOUtils.write(yugongConfig, outputStream);
            return true;
        } catch (Exception e) {
            LOG.error("upload yugong config is error !" + e);
            return false;
        }
    }
}
